package com.kasinf.sample.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class StringLengthFieldFrameDecoder extends ByteToMessageDecoder {

    private static final int LENGTH_FIELD_LENGTH = 10; // 长度头是10位字符串
    private final byte[] lengthBuffer = new byte[LENGTH_FIELD_LENGTH];
    private boolean readingLength = true;
    private int frameLength = -1;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (readingLength) {
            if (in.readableBytes() < LENGTH_FIELD_LENGTH) {
                return; // 数据不足，等待下一次读取
            }

            // 读取10位长度头
            in.readBytes(lengthBuffer);
            String lengthStr = new String(lengthBuffer, StandardCharsets.UTF_8).trim();
            try {
                frameLength = Integer.parseInt(lengthStr); // 转换为整数
            } catch (NumberFormatException e) {
                ctx.fireExceptionCaught(new IllegalArgumentException("Invalid length header: " + lengthStr));
                ctx.close();
                return;
            }

            readingLength = false;
        }

        // 读取消息体
        if (in.readableBytes() < frameLength) {
            return; // 数据未到齐，继续等待
        }

        // 提取完整消息体
        ByteBuf frame = in.readBytes(frameLength);
        out.add(frame);

        // 重置状态，准备读取下一个包
        readingLength = true;
        frameLength = -1;
    }
}
